package com.alibaba.otter.canal.adapter.launcher.config;

import com.alibaba.otter.canal.adapter.launcher.monitor.remote.RemoteConfigLoader;
import com.alibaba.otter.canal.adapter.launcher.monitor.remote.RemoteConfigLoaderFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * Bootstrap级别配置加载
 *
 * @author rewerma @ 2019-01-05
 * @version 1.0.0
 */
public class BootstrapConfiguration {

    @Autowired
    private Environment        env;

    private RemoteConfigLoader remoteConfigLoader = null;

    @PostConstruct
    public void loadRemoteConfig() {
        remoteConfigLoader = RemoteConfigLoaderFactory.getRemoteConfigLoader(env);
        if (remoteConfigLoader != null) {
            String canal_config_id = env.getProperty("canal.adapter.application.config.id");
            if (null == canal_config_id || canal_config_id.length() == 0) {
                throw new RuntimeException("未配置 application.yml 在 canal config 表中的编号");
            }
            String canal_adapter_id = env.getProperty("canal.adapter.id");
            if (null == canal_adapter_id || canal_adapter_id.length() == 0) {
                throw new RuntimeException("未配置 canal adapter 编号");
            }

            try {
                remoteConfigLoader.loadRemoteConfig(Long.parseLong(canal_config_id));
                remoteConfigLoader.loadRemoteAdapterConfigs(Long.parseLong(canal_adapter_id));
                remoteConfigLoader.startMonitor(Long.parseLong(canal_config_id), Long.parseLong(canal_adapter_id)); // 启动监听
            } catch (NumberFormatException e) {
                throw new RuntimeException("将 canal config id 或 canal adapter id 转换为 Long 类型出错");
            }
        }
    }

    @PreDestroy
    public synchronized void destroy() {
        if (remoteConfigLoader != null) {
            remoteConfigLoader.destroy();
        }
    }
}
